DECLARE @DATE_UPDATE NVARCHAR(100)=(SELECT MAX(CONVERT(NVARCHAR(8), BUSINESS_DATE,112)) FROM  SERVER74.BICDATA.DBO.BALANCE_LIVE)
DECLARE @MONTH NVARCHAR(100)
if(CAST(DATEPART(d, @DATE_UPDATE) AS VARCHAR)<10)
begin
set @MONTH=(SELECT MAX(CONVERT(NVARCHAR(6), dateadd(m,-2,BUSINESS_DATE),112)) FROM  SERVER74.BICDATA.DBO.BALANCE_LIVE)
end
else 
begin
set @MONTH=(SELECT MAX(CONVERT(NVARCHAR(6), dateadd(m,-1,BUSINESS_DATE),112)) FROM  SERVER74.BICDATA.DBO.BALANCE_LIVE)
end

EXEC('IF EXISTS
      (SELECT *
         FROM SMES360CUSTOMERDEGREE.DBO.SYSOBJECTS O
        WHERE O.XTYPE IN (''U'') AND O.NAME = ''DATE_EM_REPORT'')
        DROP TABLE DATE_EM_REPORT')

EXEC('
SELECT MAX(RIGHT(TABLE_NAME,8))  MAX_DATE_ENDMONTH, '+@DATE_UPDATE+' AS DATE_UPDATE, '+@MONTH+' AS MAX_MONTH, ''false'' as IS_UPDATE
INTO DATE_EM_REPORT 
FROM SERVER74.SME.INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE ''INCENTIVE'+@MONTH+'%''')

